package com.zz.springboot.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 拷贝工具类，方便引用对象之间的拷贝
 * <p>
 * 底层核心API：org.springframework.beans包中 BeanUtils.copy()
 */
@Slf4j
public class CloneUtils {
    /**
     * 引用对象拷贝
     * <p>
     * @addition 为了避免在拷贝时还要预先创建一个目标对象传入，这里目标对象直接传入一个Class对象
     */
    public static <T, E> E clone(T sourceBean, Class<E> targetClass) {
        if (sourceBean == null) {
            return null;
        }
        E targetBean = null;
        try {
            targetBean = targetClass.newInstance();
            BeanUtils.copyProperties(sourceBean, targetBean);   //核心
        } catch (Exception e) {
            log.error("------------------将对象{}拷贝给对象{}时出错", sourceBean, targetBean);
            throw new RuntimeException();   //抛给上层模块
        }

        return targetBean;
    }


    /**
     * 拷贝数组对象
     */
    public static <T, E> List<E> batchClone(List<T> sourceList, Class<E> targetClass) {
        if (sourceList == null) {
            return null;
        }
        List<E> targetList = new ArrayList<>();
        for (T sourceBean : sourceList) {
            targetList.add(clone(sourceBean, targetClass));
        }
        return targetList;
    }
}
